import threading
import tkinter as tk
from tkinter import scrolledtext
import webbrowser
from tkinter import ttk
from multiping import MultiPing
from port_scan import ConfigWin
import py_config
from configparser import ConfigParser

class MyUi:
    def __init__(self,root:tk.Tk,config_:ConfigParser):
        self.root=root
        self.config=config
        self.init_menu()
        self.init_ui()

    def init_menu(self):
        window = self.root
        # 创建一个主目录菜单，也被称为顶级菜单
        main_menu = tk.Menu(window)
        main_menu.add_command(label="端口监听查询",command=lambda: ConfigWin(self.root,self.config).mainloop())
        main_menu.add_command(label="更新程序",command=lambda: webbrowser.open("https://gitee.com/zhang_jie_sc/tools/releases"))
        window.configure(menu=main_menu)

    def init_ui(self):
        window=self.root
        label = tk.Label(window, text="请输入要检测的网段（例如：192.168.0）:", font=("Arial", 12))
        label.pack(pady=10)
        entry_text_var = tk.StringVar()  # 创建StringVar变量
        ip_scope=self.config.get('Ping','address_scope')
        entry_text_var.set(ip_scope)  # 设置初始值
        self.entry = tk.Entry(window, width=20, justify='center', font=('Arial', 12), textvariable=entry_text_var)
        self.entry.pack()
        self.btn_detect = tk.Button(window, text="检测", command=self.check_unused_ips_thread, font=("Arial", 12))
        self.btn_detect.pack(pady=10)

        self.v = tk.IntVar()
        self.v.set(1)
        rad_showall = tk.Radiobutton(window, text="显示所有", variable=self.v, value=0)
        rad_showall.pack()
        rad_showok = tk.Radiobutton(window, text="显示成功", variable=self.v, value=1)
        rad_showok.pack()

        self.progress_bar = ttk.Progressbar(window, orient=tk.HORIZONTAL, length=200, mode='determinate')
        self.progress_bar.pack(pady=10)
        self.output = scrolledtext.ScrolledText(window, width=40, height=50, font=("Arial", 12))
        self.output.pack(pady=10)

    def check_unused_ips(self):
        self.btn_detect.configure(state=tk.DISABLED)
        ip_range = self.entry.get()
        self.output.delete(1.0, tk.END)
        address = ["{0}.{1}".format(ip_range, i) for i in range(0, 256)]
        # Create a MultiPing object to test three hosts / addresses
        mp = MultiPing(address)
        # Send the pings to those addresses
        mp.send()
        timeout=self.config.getint('Ping','timeout')
        (ok, fail) = mp.receive(timeout)
        ok_keys=sorted(ok.keys(),key=lambda x:int(x.split('.')[-1]))
        displayAddr = ["{0}.{1}".format(ip_range, i) for i in range(0, 256)] if self.v.get() == 0 else ok_keys
        self.progress_bar['maximum'] = len(displayAddr)
        self.progress_bar['value'] = 0
        for i in displayAddr:
            delay = "{:.2f}".format(ok[i] * 1000) if i in ok else None
            fg_color = "green" if i in ok else "red"
            output=self.output
            output.tag_configure(fg_color, foreground=fg_color)  # 创建颜色标签
            output.insert(tk.END, '{0}:{1} ms\n'.format(i, delay), fg_color)
            output.see(tk.END)
            self.progress_bar['value'] += 1
            self.root.update_idletasks()
        self.btn_detect.configure(state=tk.NORMAL)

    def check_unused_ips_thread(self):
        self.config.set('Ping','address_scope',self.entry.get())
        py_config.write_config(self.config,'./pingtool.ini')
        thread1 = threading.Thread(target=self.check_unused_ips)
        thread1.start()

#  pyinstaller -F -c --uac-admin -i .\img\ip_set.ico -n PingTool .\pingTool_ui.py --additional-hooks-dir .\
if __name__=='__main__':
    root = tk.Tk()
    root.title("已使用的IP地址检测工具")
    root.geometry("400x500")
    config=py_config.read_config('./pingtool.ini')
    ui=MyUi(root,config)
    root.mainloop()